#!/bin/bash

source /home/shell/util.sh

mysql_file=`curl -sL https://dev.mysql.com/downloads/repo/yum/|grep mysql80-community-release-el8|perl -pe "s/.*\((.*)\).*/\1/g"`;

# 安装源
rpm -ivh https://dev.mysql.com/get/${mysql_file}
yum module -y disable mysql

if [ ! -f "/etc/yum.repos.d/epel.repo" ]; then
    rpm -ivh http://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm
    rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-8
fi
# 安装mysql-server
yum install -y mysql-community-server expect sshpass

mkdir -p /var/log/mysql/
chcon -R -t mysqld_db_t /var/log/mysql
chown mysql:mysql /var/log/mysql
# chcon -R --reference=/var/lib/mysql /var/log/mysql

# 推荐配置
\cp -f /home/shell/support/my.cnf /etc/my.cnf

# 服务启动
systemctl enable --now mysqld.service
# ausearch -c 'mysqld' --raw | audit2allow -M my-mysqld
# semodule -i my-mysqld.pp
# rm -rf my-mysqld.pp my-mysqld.te
# systemctl enable --now mysqld.service

# 设置参数
read -p "请输入mysql root密码[123456]：" mysql_passwd
mysql_passwd=${mysql_passwd:-"123456"};

# 改密码
printInfo "修改root密码";
temp_passwd=`grep 'temporary password' /var/log/mysql/mysqld.log | sed -r 's/.*root@localhost:\s*(.*)/\1/g'`;
printInfo "临时密码是：${temp_passwd}"
# 临时密码环境
expect <<EOF
    spawn mysql_config_editor set --login-path=temp_path --host=localhost --user=root --password
    expect {
        "password" {send "${temp_passwd}\n";exp_continue}
        "exists" {send "y\n";interact}
    }
EOF
mysql --login-path=temp_path --connect-expired-password<<EOF
alter user 'root'@'localhost' identified by 'W4AW^nLi3u3I6&7Es81!uHhS%DbRn&ag';
set global validate_password.policy=0;
set global validate_password.length=4;
alter user 'root'@'localhost' identified by '$mysql_passwd';
flush privileges;
EOF
# 用户配置密码环境
expect <<EOF
    spawn mysql_config_editor set --login-path=local --host=localhost --user=root --password
    expect {
        "password" {send "$mysql_passwd\n";exp_continue}
        "exists" {send "y\n";interact}
    }
EOF
# 删除临时密码环境
mysql_config_editor remove --login-path=temp_path

# mysqladmin -u root password $mysql_passwd

# root账户授权
mysql --login-path=local --connect-expired-password -e "use mysql;update user set host='%' where user='root';FLUSH PRIVILEGES;GRANT ALL PRIVILEGES ON *.* TO 'root'@'%';FLUSH PRIVILEGES;"
# 授权root system_user权限
mysql --login-path=local --connect-expired-password -e "GRANT system_user on *.* to 'root';FLUSH PRIVILEGES;"
# 创建dev_user用户
mysql --login-path=local --connect-expired-password -e "CREATE USER 'dev_user'@'%' IDENTIFIED WITH mysql_native_password BY '$mysql_passwd';GRANT ALL PRIVILEGES ON *.* TO 'dev_user'@'%';FLUSH PRIVILEGES;"

# 防火墙设置
firewall-addservice mysql

# 清理
rm -rf /etc/yum.repos.d/mysql-*

# mysql信息

printInfo "================"
printInfo "地址：$host_addr:3306"
printInfo "root密码：$mysql_passwd"
printInfo "dev_user密码：$mysql_passwd"
printInfo "生效配置：/etc/my.cnf"
echo -e "`cat /etc/my.cnf|grep -v "#"|grep -e '.*=.*'`"
printInfo "================"